import { CONFIG } from '@/constants/config';
import type { ApiResponse } from '@/types';
import { message } from 'antd';
import axios from 'axios';

const request = axios.create({
  baseURL: CONFIG.API.BASE_URL,
  timeout: CONFIG.API.TIMEOUT,
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem(CONFIG.CACHE.TOKEN_KEY);
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data as ApiResponse<any>;
    if (res.code !== 0) {
      message.error(res.message || '请求失败');
      return Promise.reject(new Error(res.message || '请求失败'));
    }
    return res.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      // 处理未授权
      localStorage.removeItem(CONFIG.CACHE.TOKEN_KEY);
      localStorage.removeItem(CONFIG.CACHE.USER_INFO_KEY);
      window.location.href = '/login';
    }
    message.error(error.message || '网络错误');
    return Promise.reject(error);
  },
);

export default request;
